<template>
  <div class="smart-list-view">
    <!-- 清单头部 -->
    <div class="list-header">
      <div class="list-info">
        <v-icon 
          :icon="currentList?.icon || 'mdi-format-list-bulleted'" 
          :color="currentList?.color || 'primary'"
          size="large"
          class="mr-3"
        />
        <div>
          <h2 class="list-title">{{ currentList?.name || '任务' }}</h2>
          <p class="list-subtitle">
            {{ taskStats.total }} 个任务
            <span v-if="taskStats.completed > 0">
              ，{{ taskStats.completed }} 个已完成
            </span>
            <span v-if="taskStats.overdue > 0" class="text-error">
              ，{{ taskStats.overdue }} 个已逾期
            </span>
          </p>
        </div>
      </div>
      
      <div class="list-actions">
        <v-menu>
          <template #activator="{ props }">
            <v-btn
              icon="mdi-dots-vertical"
              variant="text"
              v-bind="props"
            />
          </template>
          
          <v-list density="compact">
            <v-list-item @click="sortBy = 'dueDate'">
              <template #prepend>
                <v-icon icon="mdi-sort-calendar-ascending" size="small" />
              </template>
              <v-list-item-title>按截止时间排序</v-list-item-title>
            </v-list-item>
            
            <v-list-item @click="sortBy = 'priority'">
              <template #prepend>
                <v-icon icon="mdi-sort-variant" size="small" />
              </template>
              <v-list-item-title>按优先级排序</v-list-item-title>
            </v-list-item>
            
            <v-list-item @click="sortBy = 'createdAt'">
              <template #prepend>
                <v-icon icon="mdi-sort-clock-ascending" size="small" />
              </template>
              <v-list-item-title>按创建时间排序</v-list-item-title>
            </v-list-item>
            
            <v-divider />
            
            <v-list-item @click="showCompleted = !showCompleted">
              <template #prepend>
                <v-icon 
                  :icon="showCompleted ? 'mdi-eye-off' : 'mdi-eye'" 
                  size="small" 
                />
              </template>
              <v-list-item-title>
                {{ showCompleted ? '隐藏' : '显示' }}已完成任务
              </v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </div>
    </div>

    <!-- 任务统计信息 -->
    <div class="task-stats" v-if="taskStats.total > 0">
      <v-card class="stats-card" elevation="0" variant="outlined">
        <v-card-text class="pa-4">
          <v-row>
            <v-col cols="6" md="3">
              <div class="stat-item">
                <div class="stat-value text-primary">{{ taskStats.total }}</div>
                <div class="stat-label">总任务</div>
              </div>
            </v-col>
            <v-col cols="6" md="3">
              <div class="stat-item">
                <div class="stat-value text-success">{{ taskStats.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </v-col>
            <v-col cols="6" md="3">
              <div class="stat-item">
                <div class="stat-value text-warning">{{ taskStats.pending }}</div>
                <div class="stat-label">待完成</div>
              </div>
            </v-col>
            <v-col cols="6" md="3">
              <div class="stat-item">
                <div class="stat-value text-info">{{ taskStats.completionRate }}%</div>
                <div class="stat-label">完成率</div>
              </div>
            </v-col>
          </v-row>
          
          <v-row v-if="taskStats.overdue > 0 || taskStats.important > 0 || taskStats.dueToday > 0" class="mt-2">
            <v-col cols="4" v-if="taskStats.overdue > 0">
              <div class="stat-item">
                <div class="stat-value text-error">{{ taskStats.overdue }}</div>
                <div class="stat-label">已逾期</div>
              </div>
            </v-col>
            <v-col cols="4" v-if="taskStats.important > 0">
              <div class="stat-item">
                <div class="stat-value text-amber">{{ taskStats.important }}</div>
                <div class="stat-label">重要任务</div>
              </div>
            </v-col>
            <v-col cols="4" v-if="taskStats.dueToday > 0">
              <div class="stat-item">
                <div class="stat-value text-purple">{{ taskStats.dueToday }}</div>
                <div class="stat-label">今日到期</div>
              </div>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
    </div>

    <!-- 任务添加区域 -->
    <div class="task-input-section">
      <v-text-field
        v-model="newTaskTitle"
        placeholder="添加任务"
        variant="outlined"
        density="compact"
        hide-details
        @keyup.enter="addNewTask"
        @click="showTaskDialog = true"
      >
        <template #prepend-inner>
          <v-icon icon="mdi-plus" size="small" />
        </template>
        
        <template #append>
          <v-btn
            icon="mdi-send"
            size="small"
            variant="text"
            :disabled="!newTaskTitle.trim()"
            @click="addNewTask"
          />
        </template>
      </v-text-field>
    </div>

    <!-- 任务列表 -->
    <div class="task-list">
      <!-- 未完成任务 -->
      <div v-if="pendingTasks.length > 0" class="task-section">
        <TransitionGroup name="task" tag="div">
          <div
            v-for="task in pendingTasks"
            :key="task.id"
            class="task-item"
          >
            <SmartTaskItem
              :task="task"
              @toggle="toggleTask"
              @edit="editTask"
              @delete="deleteTask"
              @duplicate="duplicateTask"
              @update-important="updateTaskImportant"
            />
          </div>
        </TransitionGroup>
      </div>

      <!-- 已完成任务 -->
      <div v-if="showCompleted && completedTasks.length > 0" class="task-section">
        <v-divider class="my-4" />
        <div class="section-header">
          <span class="section-title">已完成 ({{ completedTasks.length }})</span>
          <v-btn
            icon="mdi-delete-sweep"
            size="small"
            variant="text"
            color="error"
            @click="clearCompletedTasks"
          />
        </div>
        
        <TransitionGroup name="task" tag="div">
          <div
            v-for="task in completedTasks"
            :key="task.id"
            class="task-item completed"
          >
            <SmartTaskItem
              :task="task"
              @toggle="toggleTask"
              @edit="editTask"
              @delete="deleteTask"
              @duplicate="duplicateTask"
              @update-important="updateTaskImportant"
            />
          </div>
        </TransitionGroup>
      </div>

      <!-- 空状态 -->
      <div v-if="displayTasks.length === 0" class="empty-state">
        <v-icon icon="mdi-check-all" size="64" color="success" class="mb-4" />
        <h3 class="text-h6 mb-2">太棒了！</h3>
        <p class="text-body-2 text-medium-emphasis">
          {{ currentListId === 'completed' ? '还没有完成的任务' : '所有任务都已完成' }}
        </p>
      </div>
    </div>
    
    <!-- 任务编辑对话框 -->
    <TaskEditDialog
      v-model="showTaskDialog"
      :task="editingTask"
      :default-list-id="currentListId"
      @save="saveTask"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useTaskStore } from '@/stores/taskStore'
import { useListStore } from '@/stores/listStore'
import SmartTaskItem from './SmartTaskItem.vue'
import TaskEditDialog from './TaskEditDialog.vue'
import type { Task } from '@/stores/taskStore'

interface Props {
  currentListId: string
}

const props = defineProps<Props>()
const taskStore = useTaskStore()
const listStore = useListStore()
const sortBy = ref<'dueDate' | 'priority' | 'createdAt'>('dueDate')
const showCompleted = ref(false)
const showTaskDialog = ref(false)
const editingTask = ref<Task | null>(null)
const newTaskTitle = ref('')

// 解构store方法
const { 
  tasks, 
  addTask, 
  updateTask, 
  deleteTask: deleteTaskStore, 
  toggleTask: toggleTaskStore,
  getTasksByListId 
} = taskStore

const { lists } = listStore

// 计算属性
const currentList = computed(() => {
  return lists.find(list => list.id === props.currentListId)
})

// 排序选项
const sortOptions = [
  { title: '按截止日期', value: 'dueDate', icon: 'mdi-calendar' },
  { title: '按优先级', value: 'priority', icon: 'mdi-flag' },
  { title: '按创建时间', value: 'createdAt', icon: 'mdi-clock' }
]

// 获取当前清单的任务
const currentListTasks = computed(() => {
  return getTasksByListId(props.currentListId)
})

// 辅助方法
const sortTasks = (taskList: Task[]) => {
  const sorted = [...taskList]
  
  switch (sortBy.value) {
    case 'dueDate':
      return sorted.sort((a, b) => {
        if (!a.dueDate && !b.dueDate) return 0
        if (!a.dueDate) return 1
        if (!b.dueDate) return -1
        return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
      })
    case 'priority':
      const priorityOrder = { high: 3, medium: 2, low: 1 }
      return sorted.sort((a, b) => {
        const aPriority = priorityOrder[a.priority || 'low']
        const bPriority = priorityOrder[b.priority || 'low']
        return bPriority - aPriority
      })
    case 'createdAt':
      return sorted.sort((a, b) => {
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      })
    default:
      return sorted
  }
}

const isOverdue = (task: Task) => {
  if (!task.dueDate || task.completed) return false
  return new Date(task.dueDate) < new Date()
}

// 未完成任务
const pendingTasks = computed(() => {
  const tasks = currentListTasks.value.filter(task => !task.completed)
  return sortTasks(tasks)
})

// 已完成任务
const completedTasks = computed(() => {
  const tasks = currentListTasks.value.filter(task => task.completed)
  return sortTasks(tasks)
})

// 显示的任务
const displayTasks = computed(() => {
  const tasks = [...pendingTasks.value]
  if (showCompleted.value) {
    tasks.push(...completedTasks.value)
  }
  return tasks
})

// 任务统计
const taskStats = computed(() => {
  const total = currentListTasks.value.length
  const completed = completedTasks.value.length
  const pending = pendingTasks.value.length
  const overdue = pendingTasks.value.filter(task => isOverdue(task)).length
  const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0
  
  return { 
    total, 
    completed, 
    pending,
    overdue,
    completionRate,
    important: currentListTasks.value.filter(task => task.isImportant).length,
    dueToday: pendingTasks.value.filter(task => {
      if (!task.dueDate) return false
      const today = new Date()
      const due = new Date(task.dueDate)
      return due.toDateString() === today.toDateString()
    }).length
  }
})

// 方法
const addNewTask = () => {
  if (!newTaskTitle.value.trim()) return
  
  const taskData: Partial<Task> = {
    title: newTaskTitle.value.trim(),
    listId: props.currentListId
  }
  
  // 根据当前清单设置任务属性
  if (props.currentListId === 'important') {
    taskData.isImportant = true
  } else if (props.currentListId === 'today') {
    taskData.dueDate = new Date()
  } else if (props.currentListId === 'tomorrow') {
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    taskData.dueDate = tomorrow
  }
  
  addTask(taskData.title!, 'tasks', taskData)
  newTaskTitle.value = ''
}

const toggleTask = (taskId: string) => {
  toggleTaskStore(taskId)
}

const editTask = (task: Task) => {
  editingTask.value = task
  showTaskDialog.value = true
}

const deleteTask = (taskId: string) => {
  if (confirm('确定要删除这个任务吗？')) {
    deleteTaskStore(taskId)
  }
}

const clearCompletedTasks = () => {
  if (confirm('确定要删除所有已完成的任务吗？')) {
    completedTasks.value.forEach(task => {
      deleteTaskStore(task.id)
    })
  }
}

const duplicateTask = (task: Task) => {
  const duplicatedTask: Partial<Task> = {
    title: `${task.title} (副本)`,
    description: task.description,
    listId: task.listId,
    priority: task.priority,
    isImportant: task.isImportant,
    tags: task.tags ? [...task.tags] : undefined,
    dueDate: task.dueDate
  }
  
  addTask(duplicatedTask.title!, 'tasks', duplicatedTask)
}

const updateTaskImportant = (taskId: string, isImportant: boolean) => {
  updateTask(taskId, { isImportant })
}

const saveTask = (taskData: Partial<Task>) => {
  if (editingTask.value) {
    updateTask(editingTask.value.id, taskData)
  } else {
    addTask(taskData.title!, 'tasks', taskData)
  }
  
  showTaskDialog.value = false
  editingTask.value = null
  newTaskTitle.value = ''
}

const editList = () => {
  if (currentList.value && currentList.value.type === 'custom') {
    // 触发父组件的编辑清单事件
    // 这里需要通过事件向上传递
    console.log('编辑清单:', currentList.value)
  }
}

const deleteList = () => {
  if (currentList.value && currentList.value.type === 'custom') {
    // 触发父组件的删除清单事件
    // 这里需要通过事件向上传递
    console.log('删除清单:', currentList.value)
  }
}

// 监听清单变化，重置显示状态
watch(() => props.currentListId, () => {
  // 重置显示状态
  if (props.currentListId === 'completed') {
    showCompleted.value = true
  }
})
</script>

<style scoped>
.smart-list-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}

.task-stats {
  padding: 16px 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}

.stats-card {
  background: rgb(var(--v-theme-surface));
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 600;
  line-height: 1.2;
}

.stat-label {
  font-size: 0.75rem;
  color: rgb(var(--v-theme-on-surface-variant));
  margin-top: 2px;
}

.list-info {
  display: flex;
  align-items: center;
}

.list-title {
  font-size: 1.5rem;
  font-weight: 500;
  margin: 0;
}

.list-subtitle {
  color: rgb(var(--v-theme-on-surface-variant));
  margin: 4px 0 0 0;
  font-size: 0.875rem;
}

.task-input-section {
  padding: 16px 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}

.task-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 24px;
}

.task-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: rgb(var(--v-theme-on-surface-variant));
}

.task-item {
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.task-item.completed {
  opacity: 0.7;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  text-align: center;
}

/* 任务动画 */
.task-enter-active,
.task-leave-active {
  transition: all 0.3s ease;
}

.task-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}

.task-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.task-move {
  transition: transform 0.3s ease;
}
</style>